package city.spring.modules.system.controller;

import city.spring.modules.system.entity.DataDictionaryEntity;
import city.spring.modules.system.service.DataDictionaryService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典 控制器
 *
 * @author HouKunLin
 * @date 2020/3/26 0026 23:40
 */
@RestController
@RequestMapping("/dataDictionary")
public class DataDictionaryController extends ApiController {
    /**
     * <strong>数据字典</strong> Service
     */
    private final DataDictionaryService dataDictionaryService;
    /**
     * 实体类（数据字典）可排序字段
     */
    private final List<SFunction<DataDictionaryEntity, ?>> entityOrderFields;

    public DataDictionaryController(DataDictionaryService dataDictionaryService) {
        this.dataDictionaryService = dataDictionaryService;
        this.entityOrderFields = new ArrayList<>();
        this.entityOrderFields.add(DataDictionaryEntity::getId);
        this.entityOrderFields.add(DataDictionaryEntity::getTitle);
        this.entityOrderFields.add(DataDictionaryEntity::getType);
        this.entityOrderFields.add(DataDictionaryEntity::getEnabled);
        this.entityOrderFields.add(DataDictionaryEntity::getGmtCreate);
        this.entityOrderFields.add(DataDictionaryEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>数据字典</strong> 列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.list')")
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DataDictionaryEntity entity) {
        LambdaQueryChainWrapper<DataDictionaryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>数据字典</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.list')")
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, DataDictionaryEntity entity) {
        LambdaQueryChainWrapper<DataDictionaryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<DataDictionaryEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 获取一个 <strong>数据字典</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.info')")
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(dataDictionaryService.getById(id));
    }

    /**
     * 添加一个 <strong>数据字典</strong>
     *
     * @param entity 新增的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.add')")
    @PostMapping
    public Object add(@RequestBody DataDictionaryEntity entity) {
        dataDictionaryService.saveDataDictionaryType(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, entity.getId());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>数据字典</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.update')")
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody DataDictionaryEntity entity) {
        entity.setId(id);
        dataDictionaryService.updateDataDictionaryType(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 更新字典类型的启用状态
     *
     * @param id      字典类型ID
     * @param enabled 启用状态
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.enabled')")
    @PutMapping("{id}/enabled/{enabled}")
    public Object update(@PathVariable String id, @PathVariable Boolean enabled) {
        if (enabled != null) {
            dataDictionaryService.enabled(id, enabled);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>数据字典</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.delete')")
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        dataDictionaryService.deleteDataDictionaryType(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>数据字典</strong>
     *
     * @param ids 主键ID列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY') or hasAnyAuthority('dictionary.delete')")
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        dataDictionaryService.deleteDataDictionaryType(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>数据字典</strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DataDictionaryEntity> buildLambdaQuery(DataDictionaryEntity entity) {
        LambdaQueryChainWrapper<DataDictionaryEntity> lambdaQuery = dataDictionaryService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DataDictionaryEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTitle()), DataDictionaryEntity::getTitle, entity.getTitle());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getType()), DataDictionaryEntity::getType, entity.getType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemarks()), DataDictionaryEntity::getRemarks, entity.getRemarks());
        lambdaQuery.eq(entity.getEnabled() != null, DataDictionaryEntity::getEnabled, entity.getEnabled());
        return lambdaQuery;
    }
}
